package com.lxk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxk.pojo.RechargeOrder;
import com.lxk.dao.RechargeOrderMapper;
import com.lxk.service.RechargeOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxk.util.exception.GlobalException;
import com.lxk.vo.result.CodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.Date;

/**
 * <p>
 * 充值信息 服务实现类
 * </p>
 *
 * @author JohnSoybean
 * @since 2020-07-14
 */
@Service
public class RechargeOrderServiceImpl extends ServiceImpl<RechargeOrderMapper, RechargeOrder> implements RechargeOrderService {

    @Autowired
    private RechargeOrderMapper rechargeOrderMapper;

    @Transactional
    @Override
    public void rechargeCallBackSuccess(String outTradeNo) {
        RechargeOrder orders = getOne(new LambdaQueryWrapper<RechargeOrder>().eq(RechargeOrder::getRechargeOrderNo, outTradeNo));
        Long userId = orders.getUserId();
        Long rechargeOrderId = orders.getRechargeOrderId();
        Integer rechargeAmount = orders.getRechargeTotal();
        //是否在重复进行业务逻辑
        if (orders.getRechargeOrderProgress() == 0) {
            //更新订单进度及支付时间
            RechargeOrder updOrder = new RechargeOrder();
            updOrder.setRechargeOrderId(rechargeOrderId);
            updOrder.setRechargeOrderProgress(1);
            updOrder.setPayDate(new Date());
            int upd = rechargeOrderMapper.updateById(updOrder);
            if (upd <= 0) {
                throw new GlobalException(CodeMsg.ORDERS_UPD_ERR);
            }
            //充值
            int updRecharge = rechargeOrderMapper.incrUserWallet(userId, rechargeAmount);
            if (updRecharge <= 0) {
                throw new GlobalException(CodeMsg.RECHARGE_FAIL);
            }
        }
    }
}
